<?php

namespace IDock\Common\Tools;

class XMLTools
{
    public static function ToXML($array, $root = 'root', $header = '', $label = '', $depth = 1): string
    {

        if (is_object($array)) {
            $array = (array)$array;
        }

        $xml = '';

        if ($header) {
            $xml .= $header;
        }
        if ($root) {
            $xml .= "<$root>";
        }

        foreach ($array as $key => $val) {
            if (is_object($val)) {
                $val = (array)$val;

                if (!is_int($key)) {
                    $xml .= "<" . $key . ">";
                }
                if ($label) {
                    $xml .= "<" . $label . ">";
                }

                $xml .= self::ToXML($val, '', '', '', $depth + 1);

                if ($label) {
                    $xml .= "</" . $label . ">";
                }

                if (!is_int($key)) {
                    $xml .= "</" . $key . ">";
                }

            } elseif (is_array($val)) {
                if (!isset($val[0])) {
                    if (is_int($key) and $label) {
                        $xml .= "<" . $label . ">" . self::ToXML($val, '', '', '', $depth + 1) . "</" . $label . ">";
                    } else {
                        $xml .= "<" . $key . ">" . self::ToXML($val, '', '', '', $depth + 1) . "</" . $key . ">";
                    }
                } else {
                    $xml .= self::ToXML($val, '', '', $key, $depth + 1);
                }
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        if ($root) {
            $xml .= "</$root>";
        }
        return $xml;
    }
}